<template>
  <div class="login-page" @keyup.enter="handleLogin">
    <!-- 特效容器 -->
    <div ref="vantaRef" class="vanta-container"></div>
    <!-- 登录内容容器 -->
    <div class="login-content">
      <div class="login-container">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span class="login-title">学生宿舍管理系统</span>
          </div>
          <div class="login-form">
            <el-form ref="loginFormRef" :model="credentials" :rules="loginRules">
              <el-form-item prop="userId">
                <el-input v-model="credentials.userId" autocomplete="off" placeholder="请输入用户名" type="text">
                  <template slot="prepend"><i class="el-icon-user" style="font-size:20px"></i></template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model="credentials.password" autocomplete="off" placeholder="请输入密码" show-password>
                  <template slot="prepend">
                    <i class="el-icon-key" style="font-size:20px"></i>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item>
                <el-button :loading="loading" style="width:100%;" type="primary" @click="handleLogin">登录</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import * as THREE from 'three'
import BIRDS from 'vanta/src/vanta.birds'


export default {
  name: 'Login',
  data() {
    return {
      loading: false,
      credentials: {
        userId: '',
        password: '',
      },
      loginRules: {
        userId: [
          {validator: this.validateUserId, trigger: 'blur'},
        ],
        password: [
          {validator: this.validatePassword, trigger: 'blur'}
        ]
      },
      vantaEffect: null
    }
  },

  mounted() {
    this.vantaEffect = BIRDS({
      el: this.$refs.vantaRef,
      THREE: THREE,
      backgroundColor: 'rgba(255, 255, 255, 255)',
      backgroundAlpha: 0,
      color1: 0xff0000,
      color2: 0xd1ff,
      birdSize: 1.20,
      wingSpan: 25.00,
      speedLimit: 8.00,
      separation: 40.00
    })
  },
  beforeDestroy() {
    if (this.vantaEffect) {
      this.vantaEffect.destroy()
      this.vantaEffect = null;  // 增加这行代码
    }
  },
  methods: {
    validateUserId(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入账户'));
      } else {
        callback();
      }
    },
    validatePassword(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入密码'));
      } else {
        callback();
      }
    },
    succeed() {
      this.$message({
        message: '登录成功',
        type: 'success'
      });
    },


    handleLogin() {
      this.$refs.loginFormRef.validate().then(() => {
        this.loading = true;
        this.$axios.post('/api/users/login', this.credentials)
            .then(response => {
              // 处理登录成功的情况，比如保存用户信息到本地存储或者跳转到其他页面
              if (response.data.code === 200) {
                // 假设这是从后端获取的用户数据
                const userData = {
                  avatarUrl: response.data.data.avatarUrl,
                  clbum: response.data.data.clbum,
                  contactInfo: response.data.data.contactInfo,
                  createdAt: response.data.data.createdAt,
                  department: response.data.data.department,
                  email: response.data.data.email,
                  gender: response.data.data.gender,
                  isLocked: response.data.data.isLocked,
                  name: response.data.data.name,
                  role: response.data.data.role,
                  userId: response.data.data.userId,
                  password: null // 密码
                };
                this.succeed();
                // 在组件中保存token
                this.$store.dispatch('saveToken', response.data.data.token);
                this.$store.dispatch('saveUser', userData);
                // 跳转页面
                this.$router.push({name: 'AdminSystem'});
              } else {
                // 登录失败
                this.$message.error(response.data.msg || '登录失败');
              }
            })
            .catch(error => {
              // 登录失败
              this.$message.error(error || '登录失败');
              // 处理登录失败的情况，比如显示错误消息
            })
            .finally(() => {
              this.loading = false; // 重置loading状态
            });
      }).catch(() => {
        this.$message({
          message: '请输入账户和密码！',
          type: 'warning'
        });
      });
    }

  }
}
</script>

<style scoped>
.login-page {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden; /* 隐藏页面滚动条 */
}

.vanta-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 99%;
  height: 100%;
  z-index: -1; /* 确保特效位于页面的最底层 */
}

.login-content {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.vanta-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: linear-gradient(180deg, #009efd 0%, #2af598 100%);
}

.login-container {
  width: 375px;
}

.login-title {
  font-size: 20px;
}

.box-card {
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-form {
  padding: 20px;
}
</style>
